package com.ams.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ams.io.network.connection.Connection;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.net.NetConnection;
import com.ams.protocol.rtmp.net.NetContext;

public class RtmpHandler extends ProtocolHandler {
    final private Logger logger = LoggerFactory.getLogger(RtmpHandler.class);

    private String docRoot;
    private NetConnection netConn;
    private boolean keepAlive = true;

    public RtmpHandler(String docRoot) {
        this.docRoot = docRoot;
    }

    public void run() {
        if (conn.isClosed()) {
            close();
            return;
        }

        try {
            if (conn.available() == 0) {
                Thread.sleep(1);
            }
            // read & process rtmp message
            netConn.readAndProcessRtmpMessage();

            // play video
            netConn.play();
            
        } catch (Exception e) {
            close();
        }
    }

    public void setConnection(Connection conn) {
        this.conn = conn;
        RtmpConnection rtmp = new RtmpConnection(conn);
        netConn = new NetConnection(rtmp, new NetContext(docRoot));
    }

    public boolean isKeepAlive() {
        return keepAlive;
    }

    public ProtocolHandler handlerFactory() {
        return new RtmpHandler(docRoot);
    }

    public void close() {
        conn.close();
        keepAlive = false;
    }

}